package base.widgets;

import org.redr.canvas.OSPath;
import org.redr.canvas.RRW;
import org.redr.canvas.RedRApplication;
import org.redr.widgetGUI.core.CommitButton;
import org.redr.widgetGUI.core.GraphicsView;
import org.redr.widgetGUI.core.LineEdit;
import org.redr.widgetGUI.settings.WidgetSettings;

import base.signals.RObjectInput;

public class Plot extends RRW {
	public static final String name = "Plot";
	public static final String summary = "Generates a Plot";
	public static final String details = "General purpose widget for plotting, simply runs the R plot commands.";
	public static final String icon = OSPath.join(RedRApplication.parentDir, "coreIcons", "default.png").getAbsolutePath();
	
	private GraphicsView plotArea;
	private LineEdit plotCommand;
	private CommitButton commitButton;

	public Plot(WidgetSettings ws) {
		super(ws);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void initSignals() {
		this.addInput(new RObjectInput(this, "id1", _("R Object"), false));
		
	}

	@Override
	protected void initGUI() {
		this.plotArea	= new GraphicsView(this.gui.controlArea, (WidgetSettings) this.settings.getSettings("plotArea")
				.setSetting("label", "Plot Area")
				.setDefault("image", ""));
		this.plotCommand	=	new LineEdit(this.gui.controlArea, (WidgetSettings) this.settings.getSettings("plotCommand")
				.setSetting("label", "Plot Command")
				.setDefault("text", ""));
		this.plotCommand.widget().setToolTip("Enter an optional plot command here as you would in R.\\nThese commands can be quite complex and may be specific for the kind of plot that you want to make.\\nThe default if blank will be plot(%s)");
		this.commitButton	=	new CommitButton(this.gui.bottomAreaRight, (WidgetSettings) this.settings.getSettings("commitButton")
				.setSetting("label", "Commit"));
	}

	@Override
	protected void initVariables() {
		this.rvarSettings.setDefault("imageFile", this.makeVarName("imageFile"));
		this.settings.setDefault("data", "");
	}

	@Override
	protected void dataInput(String id, Object data, String widgetId) {
		if (id.equals("id1")){
			this.settings.setSetting("data", (String) data);
			if ( this.commitButton.processOnInput() ) this.setPlot();
		}
		
	}
	
	protected void setPlot(){
		try{
			// want to start a new graphics device, and then make the plot.
			// I'm doing this in a single call to R so that error catching is possible.
			String file	=	"\"C:/Users/Spunky/Documents/" + this.rvarSettings.getSetting("imageFile") + ".png\"";
			this.nullR(String.format("tryCatch({%s;%s}, finally = dev.off())",
					String.format("png(%s)", file),
					this.plotCommand.text().equals("") ? 
							String.format("plot(%s)", this.settings.getSetting("data")) : String.format(this.plotCommand.text(), this.settings.getSetting("data"))
					)
				);
			this.plotArea.loadPNG(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
